<?php

require_once 'authpage.php';

/**
 * Description of WallController
 *
 * @author user
 */
class WallController extends AuthpageController {

    public function _before() {
        parent::_before();
        $this->view->scripts[] = URL::base_url() . "public/js/wall/wall.js";
    }

    
    public function index($id = null, $NumberOfWall = 5) {
        if ($NumberOfWall == null) {
            $NumberOfWall = 5;
        }

        // create temporal view index
        $contentToShow = View::factory('wall/index');
        $contentToShow->view_user = $this->view_user;

        // create form to post wall
        $postwallform = View::factory('wall/postwall');
        $postwallform->action = URL::site('wall/sendWallHandling/' . $this->view_user->id . '/' . $this->view_user->wall_access);

        $all_wall = array(); // wall[0] buat header, [1] buat content, [2] buat reply comment form
        $isnextpage = false;
        $numberofWall = 0;
        $query = "SELECT * FROM `wall`";

        //set photo for wall post form
        if ($this->auth_user->user->photo_id != null) {
            $photo = new ORM('photo');
            $photo->where("`id` = " . $this->auth_user->user->photo_id)->find();
            $postwallform->wallimagesource = $photo->link;
        } else {
            $postwallform->wallimagesource = "public/image/std_wallimage.jpg";
        }
        
        //---------------------------------------
        //select wall nya
        //---------------------------------------
        $query = "
                SELECT wall.*
                FROM  `wall`
                LEFT JOIN  `wall_tag` ON ( wall.id = wall_tag.wall_id )
                WHERE (
                (`recipient` = " . $this->view_user->id . " OR `tagged` = " . $this->view_user->id . ")";

        if ($id != null) {
            $query .= " AND wall.id < $id";
        }

        $query .= ")
                ORDER BY wall.id DESC
                LIMIT 0," . $NumberOfWall;

        $contentToShow->postwallform = $postwallform;

        $query2 = "
                SELECT wall.*
                FROM  `wall`
                LEFT JOIN  `wall_tag` ON ( wall.id = wall_tag.wall_id )
                WHERE (
                `recipient` = " . $this->view_user->id . " OR `tagged` = " . $this->view_user->id . ")";

        $wall2 = new ORM('wall');
        $wall2 = $wall2->query($query2);
        $numberofWall = 0;
        $relation_status = 4;

        if ($this->auth_user->user->id != $this->view_user->id) {
            $follow = new ORM('followings');
            $follow->where("`followee` = " . $this->view_user->id . " AND `follower` = " . $this->auth_user->user->id)->find();

            if ($follow->id != null)
                $relation_status = 3;
            else
                $relation_status = 2;
        }

        $filteredwall = array();

        // bikin query wall mana aja yang bisa ditampilin
        if ($relation_status >= $this->view_user->wall_access) {
            $contentToShow->postwallform = $postwallform;

            // ambil seluruh wall yang bisa ditampilin
            $every_wall = new ORM('wall');
            $filteredwall = $every_wall->query($query);
            $numberofWall = count($wall2);
        } else {
            $contentToShow->postwallform = "";
        }


        foreach ($filteredwall as $i => $topic) {
            // bikin header wall dulu
            $header = View::factory('wall/wallheader');
            $header->i = $i;
            $header->id = $topic->id;

            $from = new ORM('user');
            $from->where("`id` = $topic->sender")->find();

            $header->from = $from->username;
            $header->sendername = $from->name;
            $header->linkprofile = URL::site("profile/?uid=" . $topic->sender);
            $header->wall_content = $topic->message;
            $datetime = explode(" ", $topic->date_stamp);
            $header->date = $datetime[0];
            $header->time = $datetime[1];

            // create reply comment form for several user
            // bikin form reply nya buat di profil sendiri dan wall di profil org yg privilege nya lebih rendah/sama dg relation_status
            $replycomment = View::factory('wall/replycomment');
            $replycomment->wall_id = $topic->id;
            $replycomment->action = URL::site('wall/replyWallHandling/' . $this->view_user->id);

            if ($this->auth_user->user->photo_id != null) {
                $sender_image = new ORM('photo');
                $sender_image->where("`id` = " . $this->auth_user->user->photo_id)->find();
                $replycomment->imagesource = $sender_image->link;
            } else {
                $replycomment->imagesource = "public/image/std_wallimage.jpg";
            }

            // add wall image
            if ($from->photo_id != null) {
                $sender_wallimage = new ORM('photo');
                $sender_wallimage->where("`id` = " . $from->photo_id)->find();
                $header->imagesource = $sender_wallimage->link;
            } else {
                $header->imagesource = "public/image/std_wallimage.jpg";
            }

            // create a delete link for several user (owner profile and wall sender)
            if (($this->auth_user->user->id == $this->view_user->id) || ($topic->sender == $this->auth_user->user->id)) {
                $header->del_wall = URL::base_url() . "wall/deleteWall/" . $topic->id . "/" . $this->view_user->id;
                $header->isidel_wall = "<img src='" . URL::base_url() . "public/image/delete.png" . "' alt='Delete' title='Delete Wall'/>";
            } else {
                $header->del_wall = "";
                $header->isidel_wall = "";
            }

            //Setting vars for viewing ...
            $count_comment = 0;
            $walls = array();
            //$walls = $this->getWallComment($topic, 5);

            //NGAMBIL KOMENNYA
            $query = "SELECT * FROM `wall_comment` WHERE `wall_id` = " . $topic->id;

            $wall_comment = new ORM('wall_comment');
            $eachwall_comment = $wall_comment->query($query);

            // tampilin setiap komen dr tiap wall
            foreach ($eachwall_comment as $post) {
                
                $post_view = View::factory('wall/wallcontent');
                $sender = new ORM('user');
                $sender->where("`id` = $post->comment_owner")->find();

                if ($sender->photo_id != null) {
                    $sender_wallimage = new ORM('photo');
                    $sender_wallimage->where("`id` = " . $sender->photo_id)->find();
                    $post_view->imagesource = $sender_wallimage->link;
                } else {
                    $post_view->imagesource = "public/image/std_wallimage.jpg";
                }

                $post_view->fullname = $sender->name;
                $post_view->username = $sender->username;
                $post_view->linkprofile = URL::site("profile/?uid=" . $post->comment_owner);
                $post_view->content = $post->comment_text;
                $post_view->datetime = $post->date_stamp;


                if (($this->auth_user->user->id == $this->view_user->id) || ($post->comment_owner == $this->auth_user->user->id)) {
                    $post_view->del_link = URL::base_url() . "wall/deleteComment/" . $post->id . "/" . $this->view_user->id;
                    $post_view->isidel_link = "<img src='" . URL::base_url() . "public/image/delete.png" . "' alt='Delete' title='Delete Comment'/>";
                } else {
                    $post_view->del_link = "";
                    $post_view->isidel_link = "";
                }

                array_push($walls, $post_view);
            }


            $header->count_comment = count($eachwall_comment);

            //Finally push those data to all_wall
            if (($this->auth_user->user->id == $this->view_user->id) || ($topic->comment_access <= $relation_status))
                array_push($all_wall, array(0 => $header, $walls, $replycomment));
            else
                array_push($all_wall, array(0 => $header, $walls, ""));
        }

        
        //Set the WALL view
        $contentToShow->walltoshow = View::factory('wall/walltoshow');
        $contentToShow->walltoshow->walls = $all_wall;

        // SET VIEW
        $this->view->content = $contentToShow;

        // AJAX REQUEST
        if (isset($_POST["ajax"]) && isset($_POST["partial"])) {
            $this->view = View::factory("ajax", array("content" => $contentToShow->walltoshow));
            
            return;
        } else if (isset($_POST["ajax"])) {
            $this->view = View::factory("ajax", array("content" => $this->view->content));
            return;
        }
    }
    

    // alamat yang akan direfer dari fungsi untuk mengambil wall2 baru
    public function newestWall($last_id = null) {
        // create temporal view index
        $contentToShow = View::factory('wall/index');
        $contentToShow->view_user = $this->view_user;

        // create form to post wall
        $postwallform = View::factory('wall/postwall');
        $postwallform->action = URL::site('wall/sendWallHandling/' . $this->view_user->id . '/' . $this->view_user->wall_access);

        $all_wall = array(); // wall[0] buat header, [1] buat content, [2] buat reply comment form
        $isnextpage = false;
        $numberofWall = 0;
        $query = "SELECT * FROM `wall`";

        //set photo for wall post form
        if ($this->auth_user->user->photo_id != null) {
            $photo = new ORM('photo');
            $photo->where("`id` = " . $this->auth_user->user->photo_id)->find();
            $postwallform->wallimagesource = $photo->link;
        } else {
            $postwallform->wallimagesource = "public/image/std_wallimage.jpg";
        }

        $contentToShow->postwallform = $postwallform;
        
        //---------------------------------------
        //select wall nya
        //---------------------------------------
        $query = "
                SELECT wall.*
                FROM  `wall`
                LEFT JOIN  `wall_tag` ON ( `wall`.`id` = `wall_tag`.`wall_id` )
                WHERE (
                (`recipient` = " . $this->view_user->id . " OR `tagged` = " . $this->view_user->id . ")";

        if ($last_id != null) {
            $query .= " AND `wall`.`id` > $last_id";
        }

        $query .= ")
                ORDER BY `wall`.`id` DESC";

        $query2 = "
                SELECT wall.*
                FROM  `wall`
                LEFT JOIN  `wall_tag` ON ( `wall`.`id` = `wall_tag`.`wall_id` )
                WHERE (
                `recipient` = " . $this->view_user->id . " OR `tagged` = " . $this->view_user->id . ")";

        $wall2 = new ORM('wall');
        $wall2 = $wall2->query($query2);
        $numberofWall = 0;
        $relation_status = 4;

        if ($this->auth_user->user->id != $this->view_user->id) {
            $follow = new ORM('followings');
            $follow->where("`followee` = " . $this->view_user->id . " AND `follower` = " . $this->auth_user->user->id)->find();

            if ($follow->id != null)
                $relation_status = 3;
            else
                $relation_status = 2;
        }

        $filteredwall = array();

        // bikin query wall mana aja yang bisa ditampilin
        if ($relation_status >= $this->view_user->wall_access) {
            $contentToShow->postwallform = $postwallform;

            // ambil seluruh wall yang bisa ditampilin
            $every_wall = new ORM('wall');
            $filteredwall = $every_wall->query($query);
            $numberofWall = count($wall2);
        } else {
            $contentToShow->postwallform = "";
        }

        foreach ($filteredwall as $i => $topic) {
            // bikin header wall dulu
            $header = View::factory('wall/wallheader');
            $header->i = $i;
            $header->id = $topic->id;

            $from = new ORM('user');
            $from->where("`id` = $topic->sender")->find();

            $header->from = $from->username;
            $header->sendername = $from->name;
            $header->linkprofile = URL::site("profile/?uid=" . $topic->sender);
            $header->wall_content = $topic->message;
            $datetime = explode(" ", $topic->date_stamp);
            $header->date = $datetime[0];
            $header->time = $datetime[1];

            // create reply comment form for several user
            // bikin form reply nya buat di profil sendiri dan wall di profil org yg privilege nya lebih rendah/sama dg relation_status
            $replycomment = View::factory('wall/replycomment');
            $replycomment->wall_id = $topic->id;
            $replycomment->action = URL::site('wall/replyWallHandling/' . $this->view_user->id);
            

            if ($this->auth_user->user->photo_id != null) {
                $sender_image = new ORM('photo');
                $sender_image->where("`id` = " . $this->auth_user->user->photo_id)->find();
                $replycomment->imagesource = $sender_image->link;
            } else {
                $replycomment->imagesource = "public/image/std_wallimage.jpg";
            }

            // add wall image
            if ($from->photo_id != null) {
                $sender_wallimage = new ORM('photo');
                $sender_wallimage->where("`id` = " . $from->photo_id)->find();
                $header->imagesource = $sender_wallimage->link;
            } else {
                $header->imagesource = "public/image/std_wallimage.jpg";
            }

            // create a delete link for several user (owner profile and wall sender)
            if (($this->auth_user->user->id == $this->view_user->id) || ($topic->sender == $this->auth_user->user->id)) {
                $header->del_wall = URL::base_url() . "wall/deleteWall/" . $topic->id . "/" . $this->view_user->id;
                $header->isidel_wall = "<img src='" . URL::base_url() . "public/image/delete.png" . "' alt='Delete' title='Delete Wall'/>";
            } else {
                $header->del_wall = "";
                $header->isidel_wall = "";
            }

            //Setting vars for viewing ...
            $walls = array();

            //NGAMBIL WALL COMMENTNYA:

            $query = "SELECT * FROM `wall_comment` WHERE `wall_id` = " . $topic->id;

            $wall_comment = new ORM('wall_comment');
            $eachwall_comment = $wall_comment->query($query);

            // tampilin setiap komen dr tiap wall
            foreach ($eachwall_comment as $post) {
                $post_view = View::factory('wall/wallcontent');

                $sender = new ORM('user');
                $sender->where("`id` = $post->comment_owner")->find();

                if ($sender->photo_id != null) {
                    $sender_wallimage = new ORM('photo');
                    $sender_wallimage->where("`id` = " . $sender->photo_id)->find();
                    $post_view->imagesource = $sender_wallimage->link;
                } else {
                    $post_view->imagesource = "public/image/std_wallimage.jpg";
                }

                $post_view->fullname = $sender->name;
                $post_view->username = $sender->username;
                $post_view->linkprofile = URL::site("profile/?uid=" . $post->comment_owner);
                $post_view->content = $post->comment_text;
                $post_view->datetime = $post->date_stamp;


                if (($this->auth_user->user->id == $this->view_user->id) || ($post->comment_owner == $this->auth_user->user->id)) {
                    $post_view->del_link = URL::base_url() . "wall/deleteComment/" . $post->id . "/" . $this->view_user->id;
                    $post_view->isidel_link = "<img src='" . URL::base_url() . "public/image/delete.png" . "' alt='Delete' title='Delete Comment'/>";
                } else {
                    $post_view->del_link = "";
                    $post_view->isidel_link = "";
                }

                array_push($walls, $post_view);
            }


            $header->count_comment = count($eachwall_comment);
            //Finally push those data to all_wall

            if (($this->auth_user->user->id == $this->view_user->id) || ($topic->comment_access <= $relation_status))
                array_push($all_wall, array(0 => $header, $walls, $replycomment));
            else
                array_push($all_wall, array(0 => $header, $walls, ""));
        }


        //Set the WALL view
        $contentToShow->walltoshow = View::factory('wall/walltoshow');
        $contentToShow->walltoshow->walls = $all_wall;
        $contentToShow->numberOfWall = $numberofWall;

        // AJAX REQUEST
        if (isset($_POST["ajax"])) {
            $this->view = View::factory("ajax", array("content" => $contentToShow->walltoshow));
            return;
        }
    }


    // masukin wall baru ke tabel wall
    public function sendWallHandling($view_user_id, $view_user_access) {
        $orm = new ORM('wall');
        $message = $_POST['content'];
        $newmessage = "";
        $loop = true;
        // ntar disini musti di cek dulu auth_user nya udah dicek belum
        $orm->recipient = $view_user_id;
        $orm->sender = $this->auth_user->user->id;

        $pos_at = strpos($message, '@');
        if ($pos_at === false)
            $loop = false;

        $usertags = array();

        while ($loop) {
            $newmessage = $newmessage . substr($message, 0, $pos_at);
            $message = substr($message, $pos_at);
            $check = false;
            $tagged = "";
            $iterate = 1;

            while (!$check) {
                if (($message[$iterate] == ' ') || ($message[$iterate] == '.') || ($message[$iterate] == ',')) {
                    $check = true;
                } else {
                    $tagged = $tagged . $message[$iterate];
                    $iterate++;
                    if ($iterate == strlen($message))
                        $check = true;
                }
            }
            $message = substr($message, $iterate);
            $user = new ORM('user');
            $user->where("`username` = '" . $tagged . "'")->find();
            if ($user->id != null) {
                $follow = new ORM('followings');
                $follow->where("`followee` = " . $this->auth_user->user->id . " AND `follower` = " . $user->id)->find();

                if ($follow->id != null) {
                    $newmessage = $newmessage . "<a href = " . URL::site("profile/?uid=" . $user->id) . " >" . $tagged . "</a>";
                    if ($user->id != $this->auth_user->user->id) {
                        array_push($usertags, $user->id);
                    }
                } else
                    $newmessage = $newmessage . "@$tagged";
            } else
                $newmessage = $newmessage . "@$tagged";

            $pos_at = strpos($message, '@');
            if ($pos_at === false)
                $loop = false;
        }

        $newmessage = $newmessage . $message;
        $orm->message = $newmessage;
        $orm->view_access = $view_user_access;
        $orm->comment_access = $view_user_access;
        $orm->save();

        $orm2 = new ORM('wall');
        $orm2->where("`id` = ( SELECT MAX(`id`) FROM `wall` )")->find();

        foreach ($usertags as $element) {
            $orm3 = new ORM('wall_tag');
            $orm3->wall_id = $orm2->id;
            $orm3->tagged = $element;
            $orm3->save();

            $this->sendNotif($element," tagged you in a ", "post");
        }

        // nambah ke tabel notifikasi kalo posting ke wall orang
        if ($view_user_id != $this->auth_user->user->id)
            $this->sendNotif($view_user_id, " posted on your ", "wall");

        URL::redirect("wall/index/?uid=" . $view_user_id);
    }
    

    // insert notification into notif table
    private function sendNotif($receiverid, $notifikasi, $wallpost) {
        $notif = new ORM('notif');
        $notif->receiver_id = $receiverid;
        $notif->content = "<a href = " . URL::site("profile/?uid=" . $this->auth_user->user->id) . " >" . $this->auth_user->user->username . "</a>" . $notifikasi .
                "<a href = " . URL::site("wall/?uid=" . $this->auth_user->user->id) . " > " . $wallpost . "</a>";
        $notif->time_stamp = time();

        $notif->save();
    }

    // insert new wall comment into wall_comment table
    public function replyWallHandling($view_user_id) {
        //Prepare vars
        $orm = new ORM('wall_comment');
        $orm->wall_id = $_POST['wall_id'];
        $orm->comment_text = $_POST['content'];
        $orm->comment_owner = $this->auth_user->user->id;
        $orm->save();

        if ($view_user_id != $this->auth_user->user->id)
            $this->sendNotif($view_user_id, " commented on your ", "wall");

        URL::redirect("wall/index/?uid=" . $view_user_id);
    }

    /*
     * delete a wall and its comment
     */

    public function deleteWall($wallId, $uid_view) {
        //delete wall nya
        $wall = new ORM('wall');
        $wall->where("`id` = $wallId")->find();
        $wall->delete();

        if ($this->auth_user->user->id == $uid_view) {
            URL::redirect("wall/index/"); // refresh page
        } else {
            URL::redirect("wall/index/?uid=" . $uid_view); // refresh page
        }
    }

    /*
     * delete a comment on a wall
     */

    public function deleteComment($wallcommentId, $uid_view) {
        $wall_comment = new ORM('wall_comment');
        $wall_comment->where("`id` = $wallcommentId")->find();
        $wall_comment->delete();

        if ($this->auth_user->user->id == $uid_view)
            URL::redirect("wall/index"); // refresh page
        else
            URL::redirect("wall/index/?uid=" . $uid_view);
    }

    // get wall comment on a wall
    public function getWallComment($topic, $limit) {
        $walls = array();

        $query = "SELECT * FROM `wall_comment` WHERE `wall_id` = " . $topic->id . " ORDER BY `id` DESC LIMIT 0," . $limit;

        $wall_comment = new ORM('wall_comment');
        $eachwall_comment = $wall_comment->query($query);

        // tampilin setiap komen dr tiap wall
        foreach ($eachwall_comment as $post) {
            $post_view = View::factory('wall/wallcontent');

            $sender = new ORM('user');
            $sender->where("`id` = $post->comment_owner")->find();

            if ($sender->photo_id != null) {
                $sender_wallimage = new ORM('photo');
                $sender_wallimage->where("`id` = " . $sender->photo_id)->find();
                $post_view->imagesource = $sender_wallimage->link;
            } else {
                $post_view->imagesource = "public/image/std_wallimage.jpg";
            }

            $post_view->fullname = $sender->name;
            $post_view->username = $sender->username;
            $post_view->linkprofile = URL::site("profile/?uid=" . $post->comment_owner);
            $post_view->content = $post->comment_text;
            $post_view->datetime = $post->date_stamp;

            
            if (($this->auth_user->user->id == $this->view_user->id) || ($post->comment_owner == $this->auth_user->user->id)) {
                $post_view->del_link = URL::base_url() . "wall/deleteComment/" . $post->id . "/" . $this->view_user->id;
                $post_view->isidel_link = "<img src='" . URL::base_url() . "public/image/delete.png" . "' alt='Delete' title='Delete Comment'/>";
            } else {
                $post_view->del_link = "";
                $post_view->isidel_link = "";
            }
            
            array_push($walls, $post_view);
        }

        return $walls;
    }
    
}

?>
